package com.zp.resource;

import java.util.ArrayList;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.springframework.stereotype.Component;

import com.sun.jersey.spi.resource.Singleton;
import com.zp.bean.common.ResultCommonVo;
import com.zp.bean.paper.AnswerResultVo;
import com.zp.bean.paper.ResultAnswerResultVo;
import com.zp.bean.paper.ResultPaperVo;
import com.zp.domain.AnswerItem;
import com.zp.domain.AnswerResult;
import com.zp.domain.Paper;
import com.zp.domain.Question;
import com.zp.resource.common.BaseServices;
import com.zp.util.Constant;
import com.zp.util.MyException;

/**
 * answer result services
 * 
 * @author chenlijun08@gmail.com
 * 
 * @version 1.0
 * 
 * @date 2014/2/22
 * 
 */
@Component
@Path("/rest/anresult")
@Singleton
public class AnswerResultServices extends BaseServices {

	/**
	 * add one AnswerResult path:/anresult/addAnResult Http:POST
	 * 
	 * @param anresult
	 * 
	 * @return Response, ResultCommonVo with JSON String
	 *         like:{"code":268,"message":"OK","totalCount":0}
	 */
	@POST
	@Path("/addAnResult")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response addAnResult(AnswerResult anresult) {
		ResultCommonVo result = new ResultCommonVo();
		try {
			jpaDao.save(anresult);
			result.setCode(Constant.SUCCESS_CODE);
			result.setMessage(Constant.OK);
		} catch (MyException e) {
			result.setCode(Constant.FAILE_CODE);
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return Response.ok(result).build();
	}

	/**
	 * update one AnswerResult path:/anresult/updateAnResult Http:PUT
	 * 
	 * @param anresult
	 * 
	 * @return Response, ResultCommonVo with JSON String
	 *         like:like:{"code":268,"message":"OK","totalCount":0}
	 */
	@PUT
	@Path("/updateAnResult")
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Response updateAnResult(AnswerResult anresult) {
		ResultCommonVo result = new ResultCommonVo();
		try {
			jpaDao.update(anresult);
			result.setCode(Constant.SUCCESS_CODE);
			result.setMessage(Constant.OK);
		} catch (MyException e) {
			result.setCode(Constant.FAILE_CODE);
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}
		return Response.ok(result).build();
	}

	/**
	 * 
	 * get all the papers which user has been done by its id
	 * path:/anresult/getPapersForUser Http:GET
	 * 
	 * @param pageNo
	 * 
	 * @param pageSize
	 * 
	 * @param userId
	 *            the id of user
	 * 
	 * @return Response, ResultAnswerResultVo with JSON String
	 *         like:{"code":268,"message"
	 *         :"OK","totalCount":1,"paper":null,"list"
	 *         :[{"id":"402881e6445c883e01445c8a74290001","name":"心理关爱"}]}
	 * 
	 */
	@GET
	@Path("/getPapersForUser")
	@Produces({ MediaType.APPLICATION_JSON })
	public Response getPapersForUser(@QueryParam("pageNo") int pageNo,
			@QueryParam("pageSize") int pageSize,
			@QueryParam("userId") String userId) {
		logger.info("getAnResultsForUser called json pageNo:" + pageNo
				+ " pageSize:" + pageSize + " userId:" + userId);
		ResultPaperVo result = new ResultPaperVo();
		if ("".equals(userId) || userId == null) {
			result.setCode(Constant.FAILE_CODE);
			result.setMessage("userId is null");

		} else {
			String jpql = "select distinct paperId from AnswerResult where author=?";
			String countSql = "select count(distinct paperId) from AnswerResult where author=?";
			List<?> list = null;
			result.setCode(Constant.SUCCESS_CODE);
			result.setMessage(Constant.OK);
			Object[] param = { userId };
			try {
				list = this.jpaDao.getResultData(pageNo, pageSize, jpql, param);
				long totalCount = this.jpaDao.getCount(countSql, param);
				result.setTotalCount(totalCount);
			} catch (MyException e) {
				result.setCode(Constant.FAILE_CODE);
				result.setMessage(e.getMessage());
				e.printStackTrace();
			}

			if (list != null && list.size() > Constant.ZERO) {
				List<Paper> lp = new ArrayList<Paper>();
				for (Object o : list) {
					String anresult = (String) o;
					try {
						lp.add((Paper) this.jpaDao.findById(Paper.class,
								anresult));
					} catch (MyException e) {
						lp.add(null);
						e.printStackTrace();
					}

				}
				result.setList(lp);

			}
		}

		return Response.ok(result).build();
	}

	/**
	 * get result for user with specific paper path:/anresult/getResultsForUser
	 * Http:GET
	 * 
	 * @param pageNo
	 * @param pageSize
	 * @param userId
	 *            the primary key of user
	 * @param paperId
	 *            the primary key of paper
	 * @return Response ResultAnswerResultVo with JSON String
	 *         like:{"code":268,"message"
	 *         :"OK","totalCount":3,"vo":null,"list":[{
	 *         "id":1,"question":{"id":"402881e6445cc3a301445cc4332b0001"
	 *         ,"title":"心理关爱题目1","questionType":"QUS00001","questionAnswer":"",
	 *         "businessType"
	 *         :null},"item":{"id":"402881e6445d4c3701445d515f8e0002"
	 *         ,"questionId"
	 *         :"402881e6445cc3a301445cc4332b0001","answerCode":"A",
	 *         "value":"心理关爱题目1答案1"},"status":"1"},{"id":2,"question":{"id":
	 *         "402881e6445cc3a301445cc4b9890002"
	 *         ,"title":"心理关爱题目2","questionType"
	 *         :"QUS00001","questionAnswer":null
	 *         ,"businessType":null},"item":{"id"
	 *         :"402881e6445d53b401445d5688d50005"
	 *         ,"questionId":"402881e6445cc3a301445cc4b9890002"
	 *         ,"answerCode":"B","value":"心理关爱题目2答案2"},"status":"1"}]}
	 */
	@GET
	@Path("/getResultsForUser")
	@Produces({ MediaType.APPLICATION_JSON })
	public Response getResultFromPaperAndUser(@QueryParam("pageNo") int pageNo,
			@QueryParam("pageSize") int pageSize,
			@QueryParam("userId") String userId,
			@QueryParam("paperId") String paperId) {
		ResultAnswerResultVo result = new ResultAnswerResultVo();
		logger.info("getResultFromPaperAndUser called json pageNo:" + pageNo
				+ " pageSize:" + pageSize + " userId:" + userId + " paperId:"
				+ paperId);
		String jpql = "from AnswerResult where author=? and paperId=?";
		String countSql = "select count(id) from AnswerResult where author=? and paperId=?";
		List<?> list = null;
		result.setCode(Constant.SUCCESS_CODE);
		result.setMessage(Constant.OK);
		Object[] param = { userId, paperId };
		try {
			list = this.jpaDao.getResultData(pageNo, pageSize, jpql, param);
			long totalCount = this.jpaDao.getCount(countSql, param);
			result.setTotalCount(totalCount);
		} catch (MyException e) {
			result.setCode(Constant.FAILE_CODE);
			result.setMessage(e.getMessage());
			e.printStackTrace();
		}

		if (list != null && list.size() > Constant.ZERO) {
			List<AnswerResultVo> lp = new ArrayList<AnswerResultVo>();
			for (Object o : list) {
				AnswerResult anresult = (AnswerResult) o;
				AnswerResultVo vo = new AnswerResultVo();
				vo.setId(anresult.getId());
				try {
					vo.setItem((AnswerItem) this.jpaDao.findById(
							AnswerItem.class, anresult.getAnswerItemId()));
				} catch (MyException e) {
					vo.setItem(null);
					e.printStackTrace();
				}
				try {
					vo.setQuestion((Question) this.jpaDao.findById(
							Question.class, anresult.getQuestionId()));
				} catch (MyException e) {
					vo.setQuestion(null);
					e.printStackTrace();
				}
				vo.setStatus(anresult.getStatus());
				lp.add(vo);

			}
			result.setList(lp);
		}
		return Response.ok(result).build();
	}

	/**
	 * get the score of specific paper with user id path:/anresult/getScore
	 * 
	 * @param userId
	 *            primary key of LoginInfo
	 * @param paperId
	 *            primary key of paper
	 * @return Response ResultCommonVo with JSON String
	 *         like:{"code":268,"message":"40","totalCount":0}
	 */
	@GET
	@Path("/getScore")
	@Produces(MediaType.APPLICATION_JSON)
	public Response getScore(@QueryParam("userId") String userId,
			@QueryParam("paperId") String paperId) {
		ResultCommonVo result = new ResultCommonVo();
		String commitjpql = "select count(a.id) from AnswerResult a,Question q where a.answerItemId=q.questionAnswer and a.author=? and a.paperId=?";
		String totalJpql = "select count(paperId)from PaperQuestion";
		Object[] queryParams = { userId, paperId };
		long correctNum = this.jpaDao.getCount(commitjpql, queryParams);
		long totalNum = this.jpaDao.getCount(totalJpql, null);
		String score = String
				.valueOf(((float) correctNum / (float) totalNum) * 100);
		result.setCode(Constant.SUCCESS_CODE);
		result.setMessage(score);
		return Response.ok(result).build();
	}
}
